package tom.vertx.core.demo08;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;

/**
 * vertx {@link io.vertx.rxjava.core.file.FileSystem} 文件操作
 * @author ZHUFEIFEI
 */
public class FileSystemDemo {

  public static void main(String[] args) {
    Vertx.vertx().deployVerticle(new V());
  }

  static class V extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {
      //检查是否存在并创建文件
      vertx.fileSystem().exists("D:/log/abc", res -> {
        if (res.succeeded()) {
          if (!res.result()) {
            vertx.fileSystem().createFile("D:/log/abc", r -> {
              System.out.println("File create");
            });
          }
        } else {
          System.err.println("Oh oh ... - cannot create the file: " + res.cause().toString());
        }
      });

      //同步复制
      vertx.fileSystem().copyBlocking("D:/log/abc", "D:/log/abc1");

      //异步复制
      vertx.fileSystem().copy("D:/log/abc1", "D:/log/abc2", res -> {
        if (res.succeeded()) {
          System.out.println("copy succeed.");
        } else {
          System.out.println("copy error => " + res.cause().toString());
        }
      });

      //写文本文件
      vertx.fileSystem().writeFile("D:/log/vertx.txt", Buffer.buffer("Hello"), res -> {
        if (res.succeeded()) {
          System.out.println("write => " + res.result());
        } else {
          System.err.println("write error => " + res.cause().toString());
        }
      });

      //读取一个文本文件
      vertx.fileSystem().readFile("D:/log/abc", res -> {
        if (res.succeeded()) {
          System.out.println("read => " + res.result());
        } else {
          System.err.println("read error => " + res.cause().toString());
        }
      });

      //打开文件并读取, setDeleteOnClose，当AsyncFile调用close或者jvm停止时删除文件
      vertx.fileSystem().open("D:/log/vertx.txt", new OpenOptions().setRead(true).setDeleteOnClose(true), res -> {
        if (res.succeeded()) {
          AsyncFile file = res.result();
          //指定位置读取，可随机读，此外还有write可实现随机写
          file.read(Buffer.buffer(), 0, 0, 1, ar -> {
            if (ar.succeeded()) {
              System.out.println("open for read => " + ar.result().toString());
            } else {
              System.err.println("open read error => " + res.cause().toString());
            }
            file.close();
          });
        } else {
          System.err.println("open error => " + res.cause().toString());
        }
      });

    //fileSystem的配置，可以在vertx实例配置VertxOptions时配置FileSystemOptions参数, 主要配置fileSystem的文件缓存是否开启、缓存目录等



    }
  }

}
